//
//  XLTaskViewController.m
//  XiangLove
//
//  Created by feng song on 2018/3/29.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLTaskViewController.h"
#import "XLHTTPSessionManager+TaskLevel.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLTalkModel.h"
#import "XLTaskTableViewCell.h"
#import "XLGetAwardSheetView.h"
#import "XLLevelUpSheetView.h"
#import "TQAFNetworkDownload.h"
@interface XLTaskViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@end

@implementation XLTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的任务";
    [self showBackButton:NULL];
    [self addTableView];
    [self addDataSetup];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH) style:UITableViewStylePlain];
    _tableView.rowHeight = 114;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorColor = [UIColor clearColor];
    [_tableView registerClass:[XLTaskTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XLTaskTableViewCell class])];
    [self.view addSubview:_tableView];
}

-(void)addDataSetup
{
    @weakify(self);
    [TQAFNetworkDownload downloadTaskUserID:@"" reqType:BaseURL reqMethod:@"/api/v1/UserTask/GetUserTaskList" andOtherKeyDict:nil successDownload:^(id successMessage) {
        @strongify(self);
        for (NSDictionary *dic in [successMessage objectForKey:@"data"]) {
            id obj = [XLTalkModel modelWithDictionary:dic];
            [self.modelArray addObject:obj];
        }
        [self.tableView reloadData];
    } failureDownload:^(id failureMessage) {
        
    }];
    
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLTaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLTaskTableViewCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    XLTalkModel *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.everyTaskLab.text = model.TaskName;
    cell.taskDescriptionLab.text = model.TaskDescription;
    NSString *integralStr = [NSString stringWithFormat:@"经验值:+%.0ld",(long)model.Integral];
    NSMutableAttributedString *integralLabstr = [[NSMutableAttributedString alloc] initWithString:integralStr];
    [integralLabstr addAttributes:@{NSForegroundColorAttributeName:RGB_HEX(0xFFBB01),NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(4,[integralStr length] - 4)];
    cell.integralLab.attributedText = integralLabstr;
    if (model.Integral == 0) {
        cell.integralLab.hidden = YES;
    }
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"])
    {
        NSString * jdBalance = [NSString stringWithFormat:@"%.0f",[model.Balance floatValue]*10];
        if ([jdBalance integerValue] > 0) {
            NSString * jdStr = [NSString stringWithFormat:@"金豆:+%.0f",[model.Balance floatValue]*10];
            NSMutableAttributedString * jdLabStr = [[NSMutableAttributedString alloc] initWithString:jdStr];
            [jdLabStr addAttributes:@{NSForegroundColorAttributeName:RGB_HEX(0xFFBB01),NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(3,[jdStr length] - 3)];
            cell.jdLab.attributedText = jdLabStr;
        }else{
            cell.jdLab.text = @"";
        }
        
    }else{

        
        NSString * jeStr = [NSString stringWithFormat:@"%.2f",[model.Money floatValue]];
        
        if ([model.TaskCode isEqualToString:@"videocard"]) {
            
            if (model.CurrentTaskNumber.integerValue > 0) {
                
                NSAttributedString * jdLabStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"+ %.1lf(%@张)",model.Money.floatValue*model.CurrentTaskNumber.floatValue,model.CurrentTaskNumber] attributes:@{NSForegroundColorAttributeName:RGB(255, 187, 1),NSFontAttributeName:[UIFont systemFontOfSize:15]}];
                cell.jdLab.attributedText = jdLabStr;
                
            }else{
                cell.jdLab.text = @"";
            }
            
        }else{
            
            if ([jeStr floatValue] > 0) {
                
                NSString * jdStr = [NSString stringWithFormat:@"金额:+%.1f元",[model.Money floatValue]];
                NSMutableAttributedString * jdLabStr = [[NSMutableAttributedString alloc] initWithString:jdStr];
                [jdLabStr addAttributes:@{NSForegroundColorAttributeName:RGB_HEX(0xFFBB01),NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(3,[jdStr length] - 3)];
                cell.jdLab.attributedText = jdLabStr;
                
            }else{
                cell.jdLab.text = @"";
            }
            
        }
        
        
        
        
    }
    
    
//    cell.progressIdLab.text = [NSString stringWithFormat:@"%ld/%ld",(long)[model.CurrentTaskNumber integerValue],(long)[model.TaskNumber integerValue]];
    cell.taskTypeBtn.tag = indexPath.row;
    
    if ([model.Status isEqualToString:@"0"]) {// 0-未完成
        [cell.taskTypeBtn setTitle:@"去完成" forState:UIControlStateNormal];
        cell.taskTypeBtn.layer.cornerRadius = 5;
        cell.taskTypeBtn.layer.borderWidth = 1;
        cell.taskTypeBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
        [cell.taskTypeBtn addTarget:self action:@selector(goTaskStatusNO:) forControlEvents:UIControlEventTouchUpInside];
        [cell.taskTypeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    }else if ([model.Status isEqualToString:@"1"])//1 -已完成,未领取
    {
        [cell.taskTypeBtn setBackgroundColor:RGB_HEX(0xFFBB01)];
        [cell.taskTypeBtn setTitle:@"领取" forState:UIControlStateNormal];
        [cell.taskTypeBtn addTarget:self action:@selector(goTaskStatusFinsh:) forControlEvents:UIControlEventTouchUpInside];
        cell.taskTypeBtn.layer.borderWidth = 0;
        cell.taskTypeBtn.layer.cornerRadius = 5;
        [cell.taskTypeBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    }else if ([model.Status isEqualToString:@"2"])//2-已领取
    {
        [cell.taskTypeBtn setTitle:@"已领取" forState:UIControlStateNormal];
        cell.taskTypeBtn.layer.cornerRadius = 5;
        cell.taskTypeBtn.layer.borderWidth = 1;
        cell.taskTypeBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [cell.taskTypeBtn setBackgroundColor:[UIColor clearColor]];
        [cell.taskTypeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    
    return cell;
}

//任务状态： 0-未完成
-(void)goTaskStatusNO:(UIButton *)btn
{
    //去完成
    
}
//任务状态： 1 -已完成,未领取
-(void)goTaskStatusFinsh:(UIButton *)btn
{
    XLTalkModel * model = [self.modelArray objectAtIndex:btn.tag];
    @weakify(self);
    [[[XLHTTPSessionManager sharedManager] getUserTaskGetRewardUserID:[[XLAccountManager shareInstance] model].Id taskID:model.Id progressID:model.ProgressId] subscribeNext:^(id x) {
        @strongify(self)
        NSLog(@"领取状态:%@",x);
        NSString * statuSuccess = x[@"success"];
        if ([statuSuccess isEqualToString:@"0"]) {
            btn.layer.borderWidth = 1;
            btn.layer.borderColor = kLightGrayColor.CGColor;
            [btn setBackgroundColor:[UIColor clearColor]];
            [btn setTitle:@"已领取" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [btn setEnabled:NO];
            
            NSString *userLevelStr   = [NSString stringWithFormat:@"%@",x[@"data"][@"UserLevel"]];
            NSString *beforUserLevel = [NSString stringWithFormat:@"%@",x[@"data"][@"BeforUserLevel"]];
            
            NSString * pointStr = [NSString stringWithFormat:@"%@",x[@"data"][@"Point"]];
            NSString * MoneyStr = [NSString stringWithFormat:@"%@",x[@"data"][@"Money"]];
            NSString * Balance  = [NSString stringWithFormat:@"%@",x[@"data"][@"Balance"]];
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"])
            {
                XLGetAwardSheetView *GetSheetView = [XLGetAwardSheetView initXLGetAwardSheetView];
                GetSheetView.jifenLabel.text =[NSString stringWithFormat:@"+%ld",(long)[pointStr integerValue]];
                NSString * jdStrs = [NSString stringWithFormat:@"%.0f",[Balance floatValue] *10];
                if((long)[pointStr integerValue] <= 0)
                {
                    GetSheetView.jifenContent.text = @"";
                    GetSheetView.jifenLabel.text = @"";
                    GetSheetView.jifenNumHeight.constant = 1;
                    GetSheetView.jifenLabelHeight.constant = 1;
                }
                if ([jdStrs integerValue] > 0) {
                    GetSheetView.Typelabel.text = @"金豆";
                    GetSheetView.goldBeansLabel.text = [NSString stringWithFormat:@"+%.0f",[Balance floatValue] *10];
                }
                GetSheetView.block = ^{
                    
                    if ([userLevelStr integerValue] >[beforUserLevel integerValue]) {
                        
                        XLLevelUpSheetView *level = [[XLLevelUpSheetView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                        level.LevelLabel.text = [NSString stringWithFormat:@"Lv.%ld",(long)[userLevelStr integerValue]];
                        NSString *string = [NSString stringWithFormat:@"最新达到的等级Lv.%ld",(long)[userLevelStr integerValue]];
                        level.bottomAlertLabel.text = string;
                        [level show];
                        
                    }
                };
                [GetSheetView show];

                
            }else{
                XLGetAwardSheetView *GetSheetView = [XLGetAwardSheetView initXLGetAwardSheetView];
                GetSheetView.jifenLabel.text =[NSString stringWithFormat:@"+%ld",(long)[pointStr integerValue]];
                if((long)[pointStr integerValue] <= 0)
                {
                    GetSheetView.jifenContent.text = @"";
                    GetSheetView.jifenLabel.text = @"";
                    GetSheetView.jifenNumHeight.constant = 1;
                    GetSheetView.jifenLabelHeight.constant = 1;
                }
                NSString * jeStr = [NSString stringWithFormat:@"%.2f",[MoneyStr floatValue]];
                if ([jeStr floatValue] > 0) {
                    GetSheetView.Typelabel.text = @"金额";
                    GetSheetView.goldBeansLabel.text = [NSString stringWithFormat:@"+%.2f元",[MoneyStr floatValue]];
                }
                GetSheetView.block = ^{
                    
                    if ([userLevelStr integerValue] >[beforUserLevel integerValue]) {
                        
                        XLLevelUpSheetView *level = [[XLLevelUpSheetView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                        level.LevelLabel.text = [NSString stringWithFormat:@"Lv.%ld",(long)[userLevelStr integerValue]];
                        NSString *string = [NSString stringWithFormat:@"最新达到的等级Lv.%ld",(long)[userLevelStr integerValue]];
                        level.bottomAlertLabel.text = string;
                        [level show];
                        
                    }
                };
                [GetSheetView show];
            }
            
            
            
        }else{
            
           [HelpTool startTipViewWithText:@"领取失败!" duration:2.0f type:kTipViewTypeNone];
        }
        
    } error:^(NSError *error) {
        NSLog(@"错误Code:%ld",(long)error.code);
        [HelpTool startTipViewWithText:@"领取失败!" duration:2.0f type:kTipViewTypeNone];
    }];
    
}
//任务状态： 2-已领取(展示状态)

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
